package com.hbt.android.kotlin.service

import android.annotation.SuppressLint
import android.content.ContentUris
import android.content.ContentValues
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.ContactsContract
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.contentValuesOf
import com.hbt.android.kotlin.R
import com.hbt.android.kotlin.learn.array
import kotlinx.android.synthetic.main.activity_content_provider.*

class LearnContentProviderActivity: AppCompatActivity() {

    private val TAG = "LearnContentProviderActivity"


    @SuppressLint("LongLogTag")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e(TAG, "onCreate ->")

        setContentView(R.layout.activity_content_provider)

        initView()
        requestPermission()

    }

    private fun initView() {
        get_contact.setOnClickListener {
            getContact()
        }

        add_contact.setOnClickListener {
            addContact()
        }

        update_contact.setOnClickListener {
            updateContact()
        }

        del_contact.setOnClickListener {
//            delContactByPhone()
            delContactByName()
        }

        get_sms.setOnClickListener {
            getSms()
        }
    }

    private fun getSms() {
        val uri = Uri.parse("content://sms")
        val resolver = contentResolver
        val cursor = resolver.query(
            uri,
            arrayOf("address", "data", "type", "body"),
            null,
            null,
            null
        )
        while (cursor!!.moveToNext()) {
            val address = cursor.getString(0)
            val date = cursor.getString(1)
            val type = cursor.getString(2)
            val body = cursor.getString(3)
            Log.e("ContentProvider", "地址:$address")
            Log.e("ContentProvider", "时间:$date")
            Log.e("ContentProvider", "类型:$type")
            Log.e("ContentProvider", "内容:$body")
            Log.e("ContentProvider", "======================")
        }
        cursor.close()
    }

    @SuppressLint("Range")
    private fun getContact() {
        Toast.makeText(this, "getContacts", Toast.LENGTH_SHORT).show()
        val resolver = contentResolver
        val uri = Uri.parse("content://com.android.contacts/data/phones")
        val cursor = resolver.query(uri, null, null, null, null)?:return
        // 将游标移动到第一行，读取联系人
        while (cursor.moveToNext()) {
            val displayName:String =
                cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))

            val phoneNumber:String =
                cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))

            Log.e("getContact", "${displayName}, ${phoneNumber}")
            Log.e("getContact", "==============================")

        }
        cursor.close()
    }

    private fun addContact() {
        val values = ContentValues()
        /*
         * 首先向RawContacts.CONTENT_URI执行一个空值插入，目的是获得系统返回的rawContactId
         * 这时后面插入data表的数据，才能使插入的联系人在通讯录里面可见
         */
        val rawContactUri: Uri = contentResolver!!.insert(ContactsContract.RawContacts.CONTENT_URI, values)!!
        val rawContactId = ContentUris.parseId(rawContactUri)
        //往data表里写入姓名数据
        values.clear()
        values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId)
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) //内容类型
        values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, "李四")
        contentResolver.insert(ContactsContract.Data.CONTENT_URI, values)

        //往data表里写入电话数据
        values.clear()
        values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId)
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, "18888888888")
        values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
        contentResolver.insert(ContactsContract.Data.CONTENT_URI, values)

        //往data表里写入Email的数据
        values.clear()
        values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId)
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
        values.put(ContactsContract.CommonDataKinds.Email.DATA, "lisi@qq.com")
        values.put(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
        contentResolver.insert(ContactsContract.Data.CONTENT_URI, values)

    }

    private fun updateContact(){
        val contactId = getContactIdByPhone(18888888888)
        val values = ContentValues()
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
        values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, "lisi")
        contentResolver.update(
            Uri.parse("content://com.android.contacts/data"),
            values,
            "${ContactsContract.Data.CONTACT_ID}=?",
            arrayOf(contactId)
        )
    }

    private fun getContactIdByPhone(phone: Long): String? {
        var contactId = ""
        val uri = Uri.parse("content://com.android.contacts/data/phones/filter/$phone")
        val cursor = contentResolver.query(
            uri,
            arrayOf(ContactsContract.Data.CONTACT_ID),
            null,
            null,
            null
        )!!
        if (cursor.moveToFirst()) {
            contactId = cursor.getString(0)
        }
        return contactId
    }

    private fun delContactByName() {
        val name = "lisi"
        contentResolver.delete(
            ContactsContract.RawContacts.CONTENT_URI,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + "=?",
            arrayOf(name)
        )
    }

    private fun delContactByPhone() {
        val phone = 18888888888
        val contactId = getContactIdByPhone(phone)
        contentResolver.delete(
            ContactsContract.RawContacts.CONTENT_URI,
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?",
            arrayOf(contactId)
        )
    }

    private fun requestPermission(){
        val readable = ActivityCompat.checkSelfPermission(
                    this,
                    android.Manifest.permission.READ_CONTACTS
                ) != PackageManager.PERMISSION_GRANTED

        val writable = ActivityCompat.checkSelfPermission(
                    this,
                    android.Manifest.permission.WRITE_CONTACTS
                ) != PackageManager.PERMISSION_GRANTED

        // 查看是否有读取联系人的权限
        if (!readable || writable) {
            // 如果未授权则请求赋权
            ActivityCompat.requestPermissions(
                this,
                arrayOf(android.Manifest.permission.READ_CONTACTS, android.Manifest.permission.WRITE_CONTACTS),
                100
            )


//            if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_CONTACTS)) {
//                // 在这里弹窗，引导用户，去设置打开读取联系人的权限
//            }
        } else {
            // 如果授权了，则直接读取联系人
            // getContact()
        }
    }



    /**
     * 请求授权的结果
     */
    @SuppressLint("LongLogTag")
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        Log.e(TAG, "onRequestPermissionsResult ->")

        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 100) {
            if (permissions[0] == android.Manifest.permission.READ_CONTACTS) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // getContacts()
                    Toast.makeText(this, "读取联系人成功", Toast.LENGTH_SHORT).show()

                } else {
                    Toast.makeText(this, "读取联系人被拒绝", Toast.LENGTH_SHORT).show()
                }
            }else if (permissions[1] == android.Manifest.permission.WRITE_CONTACTS) {
                if (grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    // getContacts()
                    Toast.makeText(this, "写联系人成功", Toast.LENGTH_SHORT).show()

                } else {
                    Toast.makeText(this, "写联系人被拒绝", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}